<?php

class Auth extends Zend_Controller_Plugin_Abstract
{
	private $_auth;
	private $_acl;
	private $_userModel;

	private $_noAuth = array('module'    => 'default',
							 'controller' => 'auth',
							 'action'     => 'login');

	private $_noAcl = array('module'     => 'default',
							'controller' => 'error',
							'action'     => 'deny');

	public function __construct()
	{
		$this->_auth = Zend_Registry::get('auth');//Zend_Auth::getInstance();
   	    $this->_acl = Acl::getInstance()->getAcl();
		$this->_userModel = new Admin_Table_Accounts();
	}

	public function preDispatch(Zend_Controller_Request_Abstract $request)
	{
	    if ($this->_auth->hasIdentity() && intval($this->_auth->getIdentity()->id) > 0) {
			$user = $this->_userModel->fetchRow('id = ' . (int)$this->_auth->getIdentity()->id);
			//print_r($user); die();
			$role = $user->findParentRow(new Admin_Table_Role())->name;
		} else {
			$this->_auth->clearIdentity();
			$role = 'guest';
		}

		$module = $request->module;
		$controller = $request->controller;
		$action = $request->action;


		$resource = 'admin:'.$module.':'.$controller;
		if (!$this->_acl->has($resource)) {
			$resource = null;
		}

		$allow = $this->AdditionalChecks($role, $resource, $action);

		if(is_null($allow))
		if (!$this->_acl->isAllowed($role, $resource, $action)) {
			if (!$this->_auth->hasIdentity()) {
				$module     = $this->_noAuth['module'];
				$controller = $this->_noAuth['controller'];
				$action     = $this->_noAuth['action'];
			} else {
				$module     = $this->_noAcl['module'];
				$controller = $this->_noAcl['controller'];
				$action     = $this->_noAcl['action'];
			}
		}

		$request -> setModuleName($module)
				 -> setControllerName($controller)
				 -> setActionName($action);
	}

	public function getUserInfo($id = null)
	{
		if ($this->_auth->hasIdentity()) {
			return $this->_userModel->GetUserInfo($id);
		}
		else {
			return null;
		}
	}

	public function AdditionalChecks($role, $resource, $action)
	{
		if($action == 'uploadphotos') return 1;
		if($action == 'upload-avatar') return 1;
		if($action == 'remove-avatar') return 1;
		if($action == 'crop') return 1;
		if($action == 'crop-object') return 1;
		if($action == 'crop-selected') return 1;

		switch ($resource.':'.$action)
		{
			default:
				return null;
		}
	}
}